package log

import (
	"fmt"
	"go.getaway.adminspro.padmins.com/untils"
	"go.getaway.adminspro.padmins.com/untils/handler"
)

func Index(c *handler.Handler) (map[string]interface{}, untils.Error) {
	where, bindValue, limit, order, e := c.BusinessCommonQuery.Build()

	if e != nil {
		return nil, untils.BusinessErrorf(e.Error())
	}
	params := map[string]string{
		"admin_id":  fmt.Sprintf("%v", c.Auth.Get("id")),
		"only_auth": c.Request.ParamsToString("only_auth", "0"),
	}
	adminIds := []interface{}{}
	if params["admin_id"] != "" {
		if params["only_auth"] == "0" {
			adminIds = c.Auth.GetChildrenRoleAdminIds(params["admin_id"], true)
		} else {
			adminIds = []interface{}{params["admin_id"]}
		}
		where += " and admin_id in (?)"
		bindValue = append(bindValue, adminIds)
	}

	total, e := c.Db.Find(fmt.Sprintf("select count(*) total from admin_operation_log where 1=1 %s", where), bindValue...)
	if e != nil {
		return nil, untils.NewBusinessError(2000, e.Error())
	}

	rows, e := c.Db.Query(fmt.Sprintf("select * from admin_operation_log where 1=1 %s %s %s", where, order, limit), bindValue...)
	if e != nil {
		return nil, untils.NewBusinessError(2000, e.Error())
	}

	return map[string]interface{}{
		"total": total["total"],
		"rows":  rows,
	}, nil
}

func Detail(c *handler.Handler) (map[string]interface{}, untils.Error) {
	params := map[string]string{
		"admin_id": fmt.Sprintf("%v", c.Auth.Get("id")),
		"id":       c.Request.ParamsToString("id", ""),
	}
	where := "id=?"
	bindValue := []interface{}{params["id"]}
	if params["admin_id"] != "" {
		adminIds := c.Auth.GetChildrenRoleAdminIds(params["admin_id"], true)
		where += " and admin_id in (?)"
		bindValue = append(bindValue, adminIds)
	}

	row, e := c.Db.Find(fmt.Sprintf("select * from admin_operation_log where %s", where), bindValue...)
	if e != nil {
		return nil, untils.NewBusinessError(2000, e.Error())
	}

	return map[string]interface{}{
		"row": row,
	}, nil
}
